package com.open.rbac.config.executor;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicLong;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.lang.NonNull;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Teamsun 线程池
 *
 * @author Riche's
 * @since 2025/4/29
 */
@EqualsAndHashCode(callSuper = true)
@Slf4j
@Data
public class OpenTaskExecutor extends ThreadPoolTaskExecutor {

    private final String poolName;

    private final AtomicLong rejectedCount = new AtomicLong(0);

    public OpenTaskExecutor(String poolName) {
        this.poolName = poolName;
    }

    @NonNull
    @Override
    public Thread newThread(@NonNull Runnable runnable) {
        Thread thread = super.newThread(runnable);
        thread.setUncaughtExceptionHandler((t, throwable) ->
                log.error("线程池内未捕获的异常", throwable)
        );
        return thread;
    }


    @NonNull
    @Override
    public void execute(@NonNull Runnable task) {
        try {
            super.execute(task);
        } catch (RejectedExecutionException e) {
            log.error("[{}]线程池执行任务异常", poolName, e);
            throw e;
        }
    }

    @NonNull
    @Override
    public Future<?> submit(@NonNull Runnable task) {
        return super.submit(task);
    }

    @NonNull
    @Override
    public <T> Future<T> submit(@NonNull Callable<T> task) {
        try {
            return super.submit(task);
        } catch (RejectedExecutionException e) {
            log.error("[{}]线程池提交任务异常", poolName, e);
            throw e;
        }
    }

    @NonNull
    @Override
    public CompletableFuture<Void> submitCompletable(@NonNull Runnable task) {
        return super.submitCompletable(task);
    }

    @NonNull
    @Override
    public <T> CompletableFuture<T> submitCompletable(@NonNull Callable<T> task) {
        return super.submitCompletable(task);
    }

}
